import 'package:flutter/material.dart';

/// Flutter Widget种类示例
class WidgetsExample extends StatefulWidget {
  const WidgetsExample({super.key});

  @override
  State<WidgetsExample> createState() => _WidgetsExampleState();
}

class _WidgetsExampleState extends State<WidgetsExample> {
  int _counter = 0;
  String _selectedDemo = 'stateless';

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Flutter Widget种类'), backgroundColor: Theme.of(context).colorScheme.inversePrimary),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 说明卡片
            Card(
              color: Colors.blue.shade50,
              child: const Padding(
                padding: EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('🎨 Widget概述', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                    SizedBox(height: 8),
                    Text(
                      'Flutter中一切都是Widget：\n'
                      '• StatelessWidget：无状态Widget\n'
                      '• StatefulWidget：有状态Widget\n'
                      '• InheritedWidget：数据共享Widget\n'
                      '• Widget生命周期管理',
                      style: TextStyle(fontSize: 14),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),

            // 选择演示类型
            SegmentedButton<String>(
              segments: const [
                ButtonSegment(value: 'stateless', label: Text('Stateless'), icon: Icon(Icons.crop_square)),
                ButtonSegment(value: 'stateful', label: Text('Stateful'), icon: Icon(Icons.auto_awesome_motion)),
                ButtonSegment(value: 'lifecycle', label: Text('生命周期'), icon: Icon(Icons.timeline)),
              ],
              selected: {_selectedDemo},
              onSelectionChanged: (Set<String> newSelection) {
                setState(() {
                  _selectedDemo = newSelection.first;
                });
              },
            ),
            const SizedBox(height: 16),

            // 根据选择显示不同内容
            if (_selectedDemo == 'stateless') ...[
              _buildStatelessDemo(),
            ] else if (_selectedDemo == 'stateful') ...[
              _buildStatefulDemo(),
            ] else if (_selectedDemo == 'lifecycle') ...[
              _buildLifecycleDemo(),
            ],
          ],
        ),
      ),
    );
  }

  Widget _buildStatelessDemo() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Card(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text('StatelessWidget（无状态Widget）', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                const SizedBox(height: 12),
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(color: Colors.grey.shade200, borderRadius: BorderRadius.circular(8)),
                  child: const Text('''class MyWidget extends StatelessWidget {
  const MyWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text('Hello'),
    );
  }
}''', style: TextStyle(fontFamily: 'monospace', fontSize: 13)),
                ),
                const SizedBox(height: 12),
                const Text(
                  '特点：\n'
                  '• 不可变：所有属性都是final\n'
                  '• 无内部状态：不会改变\n'
                  '• 性能好：可以被const优化\n'
                  '• 使用场景：展示静态内容',
                  style: TextStyle(fontSize: 14),
                ),
              ],
            ),
          ),
        ),
        const SizedBox(height: 16),

        // 实际演示
        const Card(
          child: Padding(
            padding: EdgeInsets.all(16),
            child: Column(
              children: [
                Text('演示：', style: TextStyle(fontWeight: FontWeight.bold)),
                SizedBox(height: 8),
                _StatelessDemoWidget(message: '这是一个StatelessWidget'),
                SizedBox(height: 8),
                Text(
                  '上面的Widget没有内部状态，\n每次重建都显示相同内容。',
                  textAlign: TextAlign.center,
                  style: TextStyle(color: Colors.grey),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildStatefulDemo() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Card(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text('StatefulWidget（有状态Widget）', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                const SizedBox(height: 12),
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(color: Colors.grey.shade200, borderRadius: BorderRadius.circular(8)),
                  child: const Text('''class MyWidget extends StatefulWidget {
  const MyWidget({super.key});

  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  int _count = 0;

  void _increment() {
    setState(() {
      _count++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Text('Count: \$_count');
  }
}''', style: TextStyle(fontFamily: 'monospace', fontSize: 13)),
                ),
                const SizedBox(height: 12),
                const Text(
                  '特点：\n'
                  '• 可变：有内部状态\n'
                  '• setState()：触发重建\n'
                  '• 两个类：Widget类+State类\n'
                  '• 使用场景：需要交互和更新',
                  style: TextStyle(fontSize: 14),
                ),
              ],
            ),
          ),
        ),
        const SizedBox(height: 16),

        // 实际演示
        Card(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                const Text('演示：', style: TextStyle(fontWeight: FontWeight.bold)),
                const SizedBox(height: 16),
                Text('计数器: $_counter', style: Theme.of(context).textTheme.headlineMedium),
                const SizedBox(height: 16),
                ElevatedButton.icon(onPressed: _incrementCounter, icon: const Icon(Icons.add), label: const Text('点击增加')),
                const SizedBox(height: 8),
                const Text(
                  '上面的计数器有内部状态，\n点击按钮会调用setState()更新UI。',
                  textAlign: TextAlign.center,
                  style: TextStyle(color: Colors.grey),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildLifecycleDemo() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Card(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text('StatefulWidget生命周期', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                const SizedBox(height: 12),
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(color: Colors.grey.shade200, borderRadius: BorderRadius.circular(8)),
                  child: const Text('''class _MyWidgetState extends State<MyWidget> {
  @override
  void initState() {
    super.initState();
    // 初始化：只调用一次
    print('initState');
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 依赖改变时调用
    print('didChangeDependencies');
  }

  @override
  Widget build(BuildContext context) {
    // 构建UI：可能被多次调用
    return Container();
  }

  @override
  void didUpdateWidget(MyWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    // Widget配置改变时调用
    print('didUpdateWidget');
  }

  @override
  void deactivate() {
    // Widget被移除时调用
    super.deactivate();
    print('deactivate');
  }

  @override
  void dispose() {
    // 清理资源：只调用一次
    print('dispose');
    super.dispose();
  }
}''', style: TextStyle(fontFamily: 'monospace', fontSize: 12)),
                ),
                const SizedBox(height: 16),
                const Text('生命周期顺序：', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
                const SizedBox(height: 8),
                _buildLifecycleFlow(),
              ],
            ),
          ),
        ),
        const SizedBox(height: 16),

        // 生命周期演示按钮
        FilledButton.icon(
          onPressed: () {
            Navigator.push(context, MaterialPageRoute(builder: (context) => const _LifecycleDemo()));
          },
          icon: const Icon(Icons.play_arrow),
          label: const Text('查看生命周期演示'),
        ),
      ],
    );
  }

  Widget _buildLifecycleFlow() {
    const steps = [
      '1️⃣ createState() - 创建State对象',
      '2️⃣ initState() - 初始化状态',
      '3️⃣ didChangeDependencies() - 依赖改变',
      '4️⃣ build() - 构建Widget树',
      '5️⃣ didUpdateWidget() - 配置更新',
      '6️⃣ setState() - 状态改变（触发rebuild）',
      '7️⃣ deactivate() - Widget移除',
      '8️⃣ dispose() - 释放资源',
    ];

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: steps
          .map(
            (step) => Padding(
              padding: const EdgeInsets.symmetric(vertical: 4),
              child: Text(step, style: const TextStyle(fontSize: 14)),
            ),
          )
          .toList(),
    );
  }
}

// StatelessWidget演示
class _StatelessDemoWidget extends StatelessWidget {
  const _StatelessDemoWidget({required this.message});

  final String message;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(color: Colors.blue.shade100, borderRadius: BorderRadius.circular(8)),
      child: Row(
        children: [
          const Icon(Icons.info, color: Colors.blue),
          const SizedBox(width: 8),
          Expanded(child: Text(message)),
        ],
      ),
    );
  }
}

// 生命周期演示页面
class _LifecycleDemo extends StatefulWidget {
  const _LifecycleDemo();

  @override
  State<_LifecycleDemo> createState() => _LifecycleDemoState();
}

class _LifecycleDemoState extends State<_LifecycleDemo> {
  final List<String> _logs = [];
  int _counter = 0;

  void _addLog(String message) {
    // 检查Widget是否还挂载，避免在dispose后调用setState
    if (mounted) {
      setState(() {
        _logs.add('${DateTime.now().toString().substring(11, 19)} - $message');
      });
    } else {
      // Widget已销毁，只添加日志不触发setState
      _logs.add('${DateTime.now().toString().substring(11, 19)} - $message');
    }
  }

  @override
  void initState() {
    super.initState();
    _addLog('✓ initState() 被调用');
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _addLog('✓ didChangeDependencies() 被调用');
  }

  @override
  void didUpdateWidget(_LifecycleDemo oldWidget) {
    super.didUpdateWidget(oldWidget);
    _addLog('✓ didUpdateWidget() 被调用');
  }

  @override
  void deactivate() {
    // 直接添加日志，不调用setState（因为Widget即将被移除）
    _logs.add('${DateTime.now().toString().substring(11, 19)} - ✓ deactivate() 被调用');
    super.deactivate();
  }

  @override
  void dispose() {
    // 直接添加日志，不调用setState（因为Widget已经被销毁）
    _logs.add('${DateTime.now().toString().substring(11, 19)} - ✓ dispose() 被调用');
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('生命周期演示'), backgroundColor: Theme.of(context).colorScheme.inversePrimary),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Text('计数器: $_counter', style: Theme.of(context).textTheme.headlineMedium, textAlign: TextAlign.center),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  _counter++;
                  _addLog('🔄 setState() 被调用 - build()将被触发');
                });
              },
              child: const Text('点击触发setState()'),
            ),
            const SizedBox(height: 16),
            const Text('生命周期日志：', style: TextStyle(fontWeight: FontWeight.bold)),
            const SizedBox(height: 8),
            Expanded(
              child: Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.grey.shade100,
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: Colors.grey.shade300),
                ),
                child: ListView.builder(
                  itemCount: _logs.length,
                  itemBuilder: (context, index) {
                    return Padding(
                      padding: const EdgeInsets.symmetric(vertical: 2),
                      child: Text(_logs[index], style: const TextStyle(fontFamily: 'monospace', fontSize: 12)),
                    );
                  },
                ),
              ),
            ),
            const SizedBox(height: 12),
            const Text(
              '返回上一页将触发 deactivate() 和 dispose()',
              style: TextStyle(color: Colors.grey, fontSize: 12),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }
}
